<script setup lang="ts">
import { exportStat, StatShopData } from "@/api/stat/shop";
import type { TableColumnCtx } from "element-plus";
import { statStallData, statStallList, statStallQuery } from "@/api/stat/stall";
import { getSupplierOptions } from "@/api/supplier";

defineOptions({
  name: "StatShop",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const objFormRef = ref(ElForm);

const loading = ref(false);
const total = ref(0);
const lastPage = ref(0);

const queryParams = reactive<statStallQuery>({
  pageNum: 1,
  pageSize: 10,
});
const lists = ref<statStallData[]>();
const current_role = localStorage.getItem("role_name");
const shopList = ref<any[]>([]);

const dialog = reactive({
  title: "",
  visible: false,
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  statStallList(queryParams)
    .then(({ data }) => {
      lists.value = data.data || null;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

onMounted(() => {
  getSupplierOptions().then((data) => {
    shopList.value = data.data || [];
  });

  handleQuery();
});

interface SpanMethodProps {
  row: StatShopData;
  column: TableColumnCtx<StatShopData>;
  rowIndex: number;
  columnIndex: number;
}

const objectSpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}: SpanMethodProps) => {
  if (columnIndex === 0) {
    if (row.isFirst) {
      return {
        rowspan: row.sameIndex,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};

function bindExportStat() {
  queryParams.type = "stall";

  loading.value = true;
  exportStat(queryParams || {})
    .then((response: any) => {
      const fileData = response.data;
      const fileName = decodeURI(
        response.headers["content-disposition"].split(";")[1].split("=")[1]
      );

      const fileType =
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
      const blob = new Blob([fileData], { type: fileType });
      const downloadUrl = window.URL.createObjectURL(blob);

      const downloadLink = document.createElement("a");
      downloadLink.href = downloadUrl;
      downloadLink.download = fileName;

      document.body.appendChild(downloadLink);
      downloadLink.click();

      document.body.removeChild(downloadLink);
      window.URL.revokeObjectURL(downloadUrl);
    })
    .finally(() => {
      loading.value = false;
    });
}
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form
        class="pull-left"
        ref="queryFormRef"
        :model="queryParams"
        :inline="true"
      >
        <el-form-item
          label=""
          prop="shop_id"
          style="width: 210px"
          v-if="current_role == 'sys'"
        >
          <el-select
            v-model="queryParams.shop_id"
            placeholder="请选择店铺"
            clearable
          >
            <el-option
              :label="op.title"
              v-for="op in shopList"
              :value="Number(op.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="统计时间" prop="create_time" style="width: 420px">
          <el-date-picker
            v-model="queryParams.create_time"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item prop="stall_title" label="">
          <el-input
            v-model="queryParams.stall_title"
            placeholder="档口名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <el-button type="success" class="pull-right" @click="bindExportStat()"
        >导出统计</el-button
      >
      <div class="clear"></div>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="lists"
        :span-method="objectSpanMethod"
      >
        <el-table-column label="日期" prop="cdate" />
        <el-table-column label="店铺" prop="shop_title" />
        <el-table-column label="档口名称" prop="stall_title" />
        <el-table-column label="总单量" prop="amount" />
        <el-table-column label="商品总金额" prop="total_price" />
        <el-table-column label="总打包费" prop="total_bag_price" />
      </el-table>
    </el-card>
  </div>
</template>
